import random
import asyncio
import websockets

from services.ReportQueueService import ReportQueueService


async def send(websocket, path):
	p = ReportQueueService.listen(ReportQueueService.REPORT_FOR_VELOCITY)
	while True:
		msg = p.get_message()
		print(msg)
		if not msg:
			await asyncio.sleep(random.random() * 2)
		else:
			try:
				await websocket.send(msg['data'])
			except websockets.exceptions.ConnectionClosed as e:
				print(e)
				break


class NotificationService:
	@staticmethod
	def run():
		start_server = websockets.serve(send, '127.0.0.1', 8889)
		asyncio.get_event_loop().run_until_complete(start_server)
		asyncio.get_event_loop().run_forever()


if __name__ == '__main__':
	NotificationService.run()
